import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Row,
  Select,
  Table,
} from "antd";

import { SearchOutlined } from "@ant-design/icons";

import {
  changeHosStatusRequest,
  getCityDistrictListRequest,
  getHospitalListRequest,
  getProvinceListRequest,
} from "@api/hospital/hospitalList";
import type {
  getHospitalContentType,
  getHospitalListItemType,
  getProvinceReqReturnType,
  searchHospitalListParamsType,
} from "@/api/hospital/model/hospitalListTypes";

export default function HospitalList() {
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(3);
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [search, setSearch] = useState<searchHospitalListParamsType>({});
  const [hospitalList, setHospitalList] = useState<getHospitalContentType>([]);
  const [reRender, setReRender] = useState(false);
  const [provinceList, setProvinceList] = useState<getProvinceReqReturnType>(
    []
  );
  const [cityList, setCityList] = useState<getProvinceReqReturnType>([]);
  const [districtList, setDistrictList] = useState<getProvinceReqReturnType>(
    []
  );
  const [hosTypeList, setHosTypeList] = useState<getProvinceReqReturnType>([]);
  useEffect(() => {
    setIsLoading(true);
    const getHosList = async () => {
      const re = await getHospitalListRequest(page, limit, search);
      // console.log(re);
      setHospitalList(re.content);
      setTotal(re.totalElements);
      setIsLoading(false);
    };
    getHosList();
  }, [page, limit, search, reRender]);

  useEffect(() => {
    const getProvince = async () => {
      const re = await getProvinceListRequest();
      setProvinceList(re);
    };
    getProvince();
  }, []);

  useEffect(() => {
    const getHosType = async () => {
      const re = await getCityDistrictListRequest("10000");
      setHosTypeList(re);
    };
    getHosType();
  }, []);

  interface paramType {
    fullAddress: string;
    hostypeString: string;
  }

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      width: 50,
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院Logo",
      width: 140,
      dataIndex: "logoData",
      render(logoData: string) {
        return <img width={100} src={`data:image/jpeg;base64,${logoData}`} />;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院类型",
      dataIndex: "param",
      render(param: paramType) {
        return param.hostypeString;
      },
    },
    {
      title: "详细地址",
      dataIndex: "param",

      render(param: paramType) {
        return param.fullAddress;
      },
    },

    {
      title: "状态",
      dataIndex: "status",
      render(status: 0 | 1) {
        return !status ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      dataIndex: "handle",
      width: 100,
      fixed: "right" as "right",
      render(_: any, item: getHospitalListItemType) {
        const { id, status , hoscode } = item;
        return (
          <div>
            <Button type="primary" onClick={hospitalShowHandle(id)}>
              查看
            </Button>
            <Button type="primary" onClick={hospitalScheduleHandle(hoscode)}>排班</Button>
            <Button
              type="primary"
              onClick={changeStatusHandle(id, !status ? 1 : 0)}
            >
              {!item.status ? "上线" : "下线"}
            </Button>
          </div>
        );
      },
    },
  ];

  const provinceChangeHandle = async (value: string) => {
    if (!value) return;
    const re = await getCityDistrictListRequest(value);
    setCityList(re);
    form.setFieldsValue({ cityCode: null, districtCode: null });
    setDistrictList([]);
  };

  const cityDistrictChangeHandle = async (value: string) => {
    if (!value) return;
    const re = await getCityDistrictListRequest(value);
    form.setFieldsValue({ districtCode: null });
    setDistrictList(re);
  };

  const searchHospitalListHandle = (
    fieldValue: searchHospitalListParamsType
  ) => {
    // console.log(fieldValue);
    setSearch(fieldValue);
  };

  const clearSearchHandle = () => {
    setSearch({});
  };

  const pageChangeHandle = (current: number, pageSize: number) => {
    setPage(current);
    setLimit(pageSize);
  };

  const changeStatusHandle = (id: string, status: 0 | 1) => {
    return async () => {
      await changeHosStatusRequest(id, status);
      setReRender(!reRender);
      message.success(!status ? "上线成功" : "下线成功");
    };
  };

  const hospitalShowHandle = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hospitalShow/${id}`);
    };
  };

  const hospitalScheduleHandle=(hoscode:string)=>{
    return ()=>{
      navigate('/syt/hospital/hospitalSchedule',{
        state:{
          hoscode
        }
      })
    }
  }
  return (
    <div>
      <Card>
        <Form
          name="basic"
          autoComplete="off"
          form={form}
          onFinish={searchHospitalListHandle}
        >
          <Row gutter={20}>
            <Col span={4}>
              <Form.Item name="provinceCode">
                <Select
                  placeholder="请选择省份"
                  allowClear
                  onChange={provinceChangeHandle}
                >
                  {provinceList.map((item, index) => {
                    return (
                      <Select.Option value={item.value} key={index}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="cityCode">
                <Select
                  placeholder="请选择市"
                  allowClear
                  onChange={cityDistrictChangeHandle}
                >
                  {cityList.map((item, index) => {
                    return (
                      <Select.Option value={item.value} key={index}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="districtCode">
                <Select placeholder="请选择县/区">
                  {districtList.map((item, index) => {
                    return (
                      <Select.Option value={item.value} key={index}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hostype">
                <Select placeholder="请选择医院类型">
                  {hosTypeList.map((item, index) => {
                    return (
                      <Select.Option value={item.value} key={index}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="status">
                <Select placeholder="请选择状态">
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={4}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<SearchOutlined />}
                >
                  查询
                </Button>
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item>
                <Button
                  onClick={clearSearchHandle}
                  type="default"
                  htmlType="reset"
                >
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Table
          // className={style.mt}
          columns={columns}
          rowKey="id"
          dataSource={hospitalList}
          scroll={{ x: 1300 }}
          bordered
          loading={isLoading}
          pagination={{
            current: page,
            pageSize: limit,
            total,
            showSizeChanger: true,
            pageSizeOptions: [3, 8, 15],
            showTotal() {
              return `共${total}个医院`;
            },
            onChange: pageChangeHandle,
          }}
        />
      </Card>
    </div>
  );
}
